package com.heima.comment.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 添加拦截器
 */
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //需求分析
        //从请求头中取出用户id
        String userIdStr = request.getHeader("userId");
        //放到本地线程中
        if (!StringUtils.isEmpty(userIdStr)&&!userIdStr.equals(0)){
            Integer userId = Integer.parseInt(userIdStr);
            User user = new User();
            user.setUserId(userId);
            AppThreadLocalUtil.set(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AppThreadLocalUtil.remove();
    }
}
